define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', '../../addons/calendar/js/jquery-ui.min', 'fullcalendar', 'fullcalendar-lang', 'fullcalendar-rightclick'], function ($, undefined, Backend, Table, Form, Template, undefined, Fullcalendar, undefined, undefined) {

    var Controller = {
        index: function () {
            var $event = $.event,
                $special = $event.special;
            if (typeof $special.draginit !== 'undefined') {
                $special.draginit.teardown();
                $special.draginit = $special.dragstart = $special.dragend = $special.drag = undefined;
            }
            var calendar = $('#calendar');
            var events = {
                url: "calendar/index",
                data: function () {
                    return {
                        type: $(".fc-my-button.fc-state-active").length > 0 ? 'my' : 'all',
                        admin_id: $("#c-admin_id").length > 0 ? $("#c-admin_id").val() : 0,
                        range: $("#calendar").data("fullCalendar").view.viewSpec.singleUnit
                    };
                }
            };

            var rgb2hex = function (rgb) {
                if (/^#[0-9A-F]{6}$/i.test(rgb)) {
                    return rgb;
                }
                rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

                var hex = function (x) {
                    return ("0" + parseInt(x).toString(16)).slice(-2);
                };

                return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
            };

            var append_calendar = function (data) {
                calendar.fullCalendar('renderEvent', data);
            };

            var ini_events = function (ele) {
                ele.each(function () {
                    var eventObject = $(this).data();
                    $(this).data('eventObject', eventObject);
                    $(this).draggable({
                        zIndex: 1070,
                        revert: true,
                        revertDuration: 0
                    });

                });
            };

            var add_event = function (datetime) {
                Layer.open({
                    title: "添加事件",
                    type: 1,
                    skin: 'dialog-event',
                    shadeClose: true,
                    content: $("#add-form").parent().html(),
                    success: function (layero) {
                        $(".layui-layer-content", layero).css("overflow", "visible");
                        $("input[name=type][value=calendar]", layero).trigger("click");
                        $("#c-starttime", layero).val(datetime);
                        $("#c-endtime", layero).val(datetime);
                        $("#color-chooser li a:first", layero).trigger("click");

                        Form.api.bindevent($("form[role=form]"), function (data, ret) {
                            Layer.closeAll();
                            calendar.fullCalendar('refetchEvents');
                        });
                    }
                });
            };

            var toggle_button = function () {
                $(".fc-all-button,.fc-my-button").removeClass("fc-state-active");
                $(this).addClass("fc-state-active");
                $('.selectpage').selectPageClear();
                calendar.fullCalendar('refetchEvents');
            };

            var mark_event = function (id, action) {
                var status = action === "completed" ? "completed" : "normal";
                Fast.api.ajax({
                    loading: false,
                    url: "calendar/multi",
                    data: {ids: id, params: "status=" + status}
                }, function () {
                    calendar.fullCalendar('refetchEvents');

                    return false;
                });
            };

            var mark_day = function (date, action) {
                var status = action === "completed" ? "completed" : "normal";
                Fast.api.ajax({
                    loading: false,
                    url: "calendar/multi",
                    data: {date: date, params: "status=" + status}
                }, function () {
                    calendar.fullCalendar('refetchEvents');

                    return false;
                });
            };

            var refresh_calendar = function () {
                calendar.fullCalendar('refetchEvents');
            };

            ini_events($('#external-events div.external-event'));

            //隐藏右键菜单
            $(document).on("click", function () {
                if ($(".fullcalendar-contextmenu").length > 0) {
                    $(".fullcalendar-contextmenu").remove();
                }
            });

            // 日历天右键
            $(document).on("click", "#dayrightmenu a[data-date]", function (e) {
                e.preventDefault();
                var action = $(this).data("action");
                var date = $(this).data("date");
                if (action === 'normal' || action === 'completed') {
                    mark_day(date, action);
                } else if (action === 'delete') {
                } else if (action === 'add') {
                    add_event(date);
                }
            });

            // 事件右键
            $(document).on("click", "#eventrightmenu a[data-id]", function (e) {
                e.preventDefault();
                var action = $(this).data("action");
                var id = $(this).data("id");
                if (action === 'normal' || action === 'completed') {
                    mark_event(id, action);
                } else if (action === 'edit') {
                    Fast.api.ajax({
                        loading: false,
                        url: 'calendar/edit/ids/' + id,
                        type: 'get'
                    }, function (data, ret) {
                        Layer.open({
                            title: "更新事件",
                            type: 1,
                            skin: 'dialog-event',
                            shadeClose: true,
                            content: Template("edittpl", data),
                            success: function (layero) {
                                $(".layui-layer-content", layero).css("overflow", "visible");
                                Form.api.bindevent($("#edit-form"), function (data, ret) {
                                    Layer.closeAll();
                                    refresh_calendar();
                                });
                            }
                        });
                    });
                } else if (action === 'delete') {
                    Fast.api.ajax({
                        loading: false,
                        url: "calendar/del/ids/" + id
                    }, function () {
                        calendar.fullCalendar('refetchEvents');
                        return false;
                    });
                }
            });

            var options = {
                customButtons: {
                    all: {
                        text: __('All'),
                        click: toggle_button
                    },
                    my: {
                        text: __('My'),
                        click: toggle_button
                    },
                },
                header: {
                    left: 'prev,next today all,my',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                dayClick: function (date, jsEvent, view) {
                    add_event(date.format("YYYY-MM-DD HH:mm:ss"));
                },
                eventClick: function (calEvent, jsEvent, view) {
                    mark_event(calEvent.id, $(this).hasClass("fc-completed") ? 'normal' : 'completed');
                    return;
                    var that = this;
                    var status = $(this).hasClass("fc-completed") ? "normal" : "completed";
                    Fast.api.ajax({
                        loading: false,
                        url: "calendar/multi/ids/" + calEvent.id,
                        data: {params: "status=" + status}
                    }, function () {
                        $(that).removeClass("fc-completed fc-normal");
                        if (status == "completed") {
                            $(that).addClass("fc-completed");
                        }
                        return false;
                    });
                },
                dayRightclick: function (date, jsEvent, view) {
                    console.log(123);
                    if ($(".fullcalendar-contextmenu").length > 0) {
                        $(".fullcalendar-contextmenu").remove();
                    }
                    var html = Template("dayrighttpl", {date: date.format("YYYY-MM-DD HH:mm:ss")});
                    var dropdown = $(html);
                    dropdown.css("position", "absolute").css("z-index", 99999).css("top", jsEvent.pageY + "px").css("left", jsEvent.pageX).appendTo("body");
                    dropdown.show();
                    return false;
                },
                eventRightclick: function (data, jsEvent, view) {
                    console.log(456);
                    if ($(".fullcalendar-contextmenu").length > 0) {
                        $(".fullcalendar-contextmenu").remove();
                    }
                    var html = Template("eventrighttpl", data);
                    var dropdown = $(html);
                    dropdown.css("position", "absolute").css("z-index", 99999).css("top", jsEvent.pageY + "px").css("left", jsEvent.pageX).appendTo("body");
                    dropdown.show();
                    return false;
                },
                events: events,
                navLinks: true, // can click day/week names to navigate views
                editable: true,
                displayEventTime: false,
                droppable: true,
                drop: function (date, allDay) {
                    var that = this;
                    var id = $(this).data('id');
                    var title = $(this).data('title');
                    Fast.api.ajax({
                        loading: false,
                        url: "calendar/add/ids/" + id,
                        data: {'row[starttime]': date.format(), 'row[endtime]': date.format()}
                    }, function (data, ret) {
                        append_calendar(data);
                        if ($('#drop-remove').is(':checked')) {
                            Fast.api.ajax({
                                loading: false,
                                url: "calendar/delevent/ids/" + id
                            }, function () {
                                $(that).remove();
                                return false;
                            });
                        }
                        return false;
                    }, function () {

                    });

                },
                eventRender: function (event, $el) {
                    $el.attr("title", event.title);
                },
                eventDrop: function (event, delta, revertFunc, jsEvent) {
                    Fast.api.ajax({
                        loading: false,
                        url: "calendar/edit/ids/" + event.id,
                        data: {'row[starttime]': event.start.format(), 'row[endtime]': event.end ? event.end.format() : event.start.format()}
                    }, function (data) {
                        refresh_calendar();
                        return false;
                    }, function () {
                        revertFunc();
                        return false;
                    });
                },
                eventDragStart: function (event, jsEvent) {
                    $("#calendarTrash").show();
                    $(".fc-toolbar .fc-button-group").hide();
                },
                eventDragStop: function (event, jsEvent) {
                    $(".fc-toolbar .fc-button-group").show();
                    var trashEl = jQuery('#calendarTrash');
                    var ofs = trashEl.offset();

                    var x1 = ofs.left;
                    var x2 = ofs.left + trashEl.outerWidth(true);
                    var y1 = ofs.top;
                    var y2 = ofs.top + trashEl.outerHeight(true);
                    if (jsEvent.pageX >= x1 && jsEvent.pageX <= x2 && jsEvent.pageY >= y1 && jsEvent.pageY <= y2) {
                        Fast.api.ajax({
                            loading: false,
                            url: "calendar/del/ids/" + event.id
                        }, function () {
                            calendar.fullCalendar('removeEvents', event.id);
                            return false;
                        });
                    }
                    $("#calendarTrash").hide();
                    return false;
                },
                eventResize: function (event, delta, revertFunc) {
                    Fast.api.ajax({
                        loading: false,
                        url: "calendar/edit/ids/" + event.id,
                        data: {'row[starttime]': event.start.format(), 'row[endtime]': event.end ? event.end.format() : event.start.format()}
                    }, function (data) {
                        calendar.fullCalendar('refetchEvents');
                        return false;
                    }, function () {
                        revertFunc();
                        return false;
                    });

                },
                eventAfterAllRender: function (view) {
                    if ($(".fc-all-button.fc-state-active,.fc-my-button.fc-state-active").length == 0) {
                        $(".fc-toolbar").append('<div id="calendarTrash" class="calendar-trash"><i class="fa fa-trash-o"></i><b>' + __('Drag here to delete') + '</b></div>');
                        $(".fc-all-button").addClass("fc-state-active");
                        $(".fc-toolbar .fc-left").append('<form class="form-inline"><input type="text" id="c-admin_id" name="admin_id" placeholder="' + __('Please select a user') + '" class="form-control input-sm selectpage" /></form>');
                        $(".fc-toolbar .fc-left .selectpage").data("source", Config.admins);
                        Form.events.selectpage($(".fc-toolbar .fc-left form"));
                    }
                    $("a.fc-event[href]").attr("target", "_blank");
                }
            };
            calendar.fullCalendar(options);

            var currColor = "#3c8dbc";
            // 切换颜色
            $(document).on("click", "#color-chooser > li > a", function (e) {
                var form = $(this).closest("form");
                $("#color-chooser li a", form).removeClass("active");
                $(this).addClass("active");
                currColor = $(this).css("color");
                $("input[name='row[background]']", form).val(rgb2hex(currColor));
                return false;
            });

            // 切换类型
            $(document).on("click", "input[name=type]", function (e) {
                var value = $(this).val();
                var form = $(this).closest("form");
                $("#daterange", form).toggle(value === 'calendar');
                form.attr("action", value === 'calendar' ? "calendar/add" : "calendar/addevent");
            });

            //删除事件
            $(document).on("click", ".btn-remove-event", function () {
                var id = $(this).data("id");
                var that = this;
                Fast.api.ajax({
                    loading: false,
                    url: "calendar/delevent/ids/" + id
                }, function () {
                    $(that).closest(".external-event").remove();
                });
            });

            //点击管理员
            $(document).on("change", "input[name='admin_id']", function () {
                calendar.fullCalendar('refetchEvents');
            });

            $("#color-chooser li a:first").trigger("click");
            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                Layer.closeAll();
                if ($("input[name=type]:checked").val() == 'event') {
                    var event = $("<div />");
                    event.css({"background-color": data.background, "border-color": data.background, "color": "#fff"}).addClass("external-event");
                    event.data("id", data.id);
                    event.data("title", data.title);
                    event.data("background", data.background);
                    event.html(data.title);
                    $('#external-events').prepend(event);
                    ini_events(event);
                } else {
                    append_calendar(data);
                }
                $(this).trigger("reset");
                $("input[name=type]:checked").trigger("click");
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
        }
    };
    return Controller;
});
